package cn.alcatraz.mq_02_sync;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.List;
/**
 * @Description: 消费者
 * @Author: Alcatraz
 * @Version: 1.0
 * @Date:  2022/7/26 21:09
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        // 创建消费者
        DefaultMQPushConsumer sync_consumer_group = new DefaultMQPushConsumer("sync_consumer_group");

        // 连接nameserver
        sync_consumer_group.setNamesrvAddr("127.0.0.1:9876");

        // 订阅主题
        sync_consumer_group.subscribe("sync_topic","sync");

        // 注册监听器
        sync_consumer_group.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt messageExt : list) {
                    // 接收消息
                    System.out.println(new String(messageExt.getBody(), StandardCharsets.UTF_8));
                }
                // 标记该消息已经被成功消费
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        // 消费者启动
        sync_consumer_group.start();
    }
}
